<?php

/*
 * 用户控制器
 * @author turtle
 * create_time 2017-01-03
 */


namespace App\Admin\Controllers\Users;

use App\Admin\Controllers\Controller;
use App\Admin\Models\City;
use App\Admin\Models\DeleteUser;
use App\Admin\Models\Logs;
use App\Admin\Models\Office;
use App\Admin\Models\Renter;
use App\Admin\Models\Role;
use App\Admin\Models\UploadImg;
use App\Admin\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{

    /*
     * 用户列表页面
     * @author turtle
     * create_time 2017-01-03
     */

    public function index()
    {
        $bool = User::checkUserPermissions('check_user');
        if (!$bool) {
            return redirect()
                ->route('admin.dashboard')
                ->with([
                    'message' => "您没有拥有该权限，请联系管理员",
                    'alert-type' => 'error',
                ]);
        }
        $user = Auth::user();
        $role_id = $user['role_id'];
        if ($role_id == 1) {
            $users = User::all();
        } else {
            $users = User::where('city', $user['city'])->where('mobile', '<>', 'admin')->get();
        }

        foreach ($users as $key => $user) {
            $result = City::find($user['city']);
            $city = $result->city;
            $users[$key]['address'] = $user['province'] . $city;
        }
        $edit_user = User::checkUserPermissions('edit_user');
        $add_user = User::checkUserPermissions('add_user');
        $del_user = User::checkUserPermissions('del_user');

        $datas['edit_user'] = $edit_user;
        $datas['add_user'] = $add_user;
        $datas['del_user'] = $del_user;

        $datas['users'] = $users;
        return view('admin.user', $datas);
    }

    /**
     * 获取特定条件下的员工上级
     * @author 赵世伟
     * @param Request $request
     * @return mixed|null
     * create_time 2017-2-23
     */
    public function getSuperiors(Request $request)
    {
        $city = (!empty($request->get('city_id')) || $request->get('city_id') != 'null') ? $request->get('city_id') : null;
        $role_id = (!empty($request->get('role_id'))) ? $request->get('role_id') : null;
        $user_id = (!empty($request->get('user_id'))) ? $request->get('user_id') : null;
        $user = array(
            'city' => $city,
            'role_id' => $role_id,
            'id' => $user_id,
        );
        $superiors = User::getSuperiors($user);
        return $superiors;

    }

    /*
     * 添加/编辑用户页面
     * @author turtle
     * create_time 2017-01-03
     */

    public function add($id = null)
    {
        $bool = User::checkUserPermissions('edit_user');
        $operator = Auth::user();
        if (!$bool) {
            return redirect()
                ->route('admin.dashboard')
                ->with([
                    'message' => "您没有拥有该权限，请联系管理员",
                    'alert-type' => 'error',
                ]);
        }

        $id = intval($id);
        $provinces = City::getProvince();
        $citys = null;
        $superiors = null;
        $user = null;

        if (!empty($id)) {
            $user = User::find($id);
            if (empty($user)) {
                return redirect()
                    ->route('admin.users')
                    ->with([
                        'message' => "抱歉，该用户不存在",
                        'alert-type' => 'error',
                    ]);

            } elseif ($user['city'] != $operator['city'] && $operator['id'] != 1) {
                return redirect()
                    ->route('admin.users')
                    ->with([
                        'message' => "抱歉，没有编辑该用户的权限",
                        'alert-type' => 'error',
                    ]);
            }

            $citys = City::getAll();
            foreach ($citys as $key => $city) {
                if ($city['address'] != $user['province']) {
                    unset($citys[$key]);
                }
            }
            $superiors = User::getSuperiors($user);
        }
        $roles = Role::get();

        $datas['user'] = $user;
        $datas['roles'] = $roles;
        $datas['id'] = $id;
        $datas['provinces'] = $provinces;
        $datas['citys'] = $citys;
        $datas['superiors'] = $superiors;
        return view('admin.add_user', $datas);
    }

    /*
     * 添加用户
     * @author turtle
     * create_time 2017-01-03
     */

    public
    function post_add(Request $request)
    {
        $data['province'] = trim($request->input('province'));
        $data['city'] = trim($request->input('city'));
        $data['name'] = trim($request->input('name'));
        $data['email'] = trim($request->input('email'));
        $data['mobile'] = trim($request->input('mobile'));
        $data['role_id'] = intval($request->input('role_id'));
        if ($request->input('superior') != 'null') {
            $data['superior'] = intval($request->input('superior'));
        } else {
            $data['superior'] = null;
        }
        $image = $request->file('avatar');

        $id = intval($request->input('id'));
        if (!empty($id)) {
            $bool = User::checkUserPermissions('edit_user');
            if (!$bool) {
                return redirect()
                    ->route('admin.dashboard')
                    ->with([
                        'message' => "您没有拥有该权限，请联系管理员",
                        'alert-type' => 'error',
                    ]);
            }
            $user = User::where('mobile', $data['mobile'])->first();
            if (!empty($user) && $user->id != $id) {
                return redirect()
                    ->route('admin.users.add', $id)
                    ->with([
                        'message' => "抱歉，该用户已存在",
                        'alert-type' => 'error',
                    ]);

            }
            if (!empty($request->input('password'))) {
                $data['password'] = bcrypt(trim($request->input('password')));
            }
            if (!empty($image)) {
                $data['avatar'] = UploadImg::upload($image, 'users');
            }
            $data['updated_at'] = date('Y-m-d H:m:s');
            $rs = User::where('id', $id)->update($data);
            if ($rs === false) {
                $log = "编辑用户" . $user->name . "失败";
                Logs::addLog($log);
                return redirect()
                    ->route('admin.users.add', $id)
                    ->with([
                        'message' => "抱歉，编辑用户失败",
                        'alert-type' => 'error',
                    ]);

            } else {
                $log = "编辑用户" . $user->name . "成功";
                Logs::addLog($log);
                return redirect()
                    ->route('admin.users.add', $id)
                    ->with([
                        'message' => "编辑用户成功",
                        'alert-type' => 'success',
                    ]);

            }
        } else {
            $bool = User::checkUserPermissions('add_user');
            if (!$bool) {
                return redirect()
                    ->route('admin.dashboard')
                    ->with([
                        'message' => "您没有拥有该权限，请联系管理员",
                        'alert-type' => 'error',
                    ]);
            }
            $user = User::where('mobile', $data['mobile'])->first();
            if (!empty($user)) {
                return redirect()
                    ->route('admin.users.add')
                    ->with([
                        'message' => "抱歉，该用户已存在",
                        'alert-type' => 'error',
                    ]);
            }

            if (!empty($image)) {
                $data['avatar'] = UploadImg::upload($image, 'users');
            }
            $data['password'] = bcrypt(trim($request->input('password')));

            $data['created_at'] = date('Y-m-d H:m:s');
            $data['updated_at'] = date('Y-m-d H:m:s');

            $rs = User::insert($data);

            if ($rs) {
                $log = "新增用户" . $data['name'] . "成功";
                Logs::addLog($log);
                return redirect()
                    ->route('admin.users')
                    ->with([
                        'message' => " 新增用户成功",
                        'alert-type' => 'success',
                    ]);

            } else {
                $log = "新增用户" . $data['name'] . "失败";
                Logs::addLog($log);
                return redirect()
                    ->route('admin.users')
                    ->with([
                        'message' => "新增用户失败",
                        'alert-type' => 'error',
                    ]);

            }

        }
    }

    /* 删除用户
     * @author turtle
     * create_time 2017-01-04
     */

    public
    function deleteUser($id)
    {
        $newUser = $_POST['newUser'] != 'null' ? $_POST['newUser'] : null;
        $operator = Auth::user();
        $bool = User::checkUserPermissions('del_user');
        if (!$bool) {
            return redirect()
                ->route('admin.dashboard')
                ->with([
                    'message' => "您没有拥有该权限，请联系管理员",
                    'alert-type' => 'error',
                ]);
        }
        $id = intval($id);

        $user = User::find($id);
        if (empty($user)) {
            return redirect()
                ->route('admin.users')
                ->with([
                    'message' => "抱歉，该用户不存在",
                    'alert-type' => 'error',
                ]);

        } elseif ($user['city'] != $operator['city'] && $operator['id'] != 1) {
            if (!User::isAccessToDeleteUser($user, $operator)) {
                return redirect()
                    ->route('admin.users')
                    ->with([
                        'message' => "抱歉，没有删除该用户的权限",
                        'alert-type' => 'error',
                    ]);
            }
        }
        if ($newUser == null) {
            return redirect()
                ->route('admin.users')
                ->with([
                    'message' => "抱歉，此用户下有写字楼和客源需要转移",
                    'alert-type' => 'error',
                ]);
        }
        Office::where('operator', $user['id'])->update(array('operator' => $newUser));
        Renter::where('handle_staff', $user['id'])->update(array('handle_staff' => $newUser));

        $newUserArr = User::find($newUser);
        User::where(array('superior' => $user['id'], 'id' => $newUser))->update(array('superior' => $newUserArr['superior']));
        User::where('superior', $user['id'])->update(array('superior' => $newUser));


        $rs = User::where('id', $id)->delete();
        if ($rs) {
            $log = "删除用户" . $user->name . "成功";
            Logs::addLog($log);
            $deleteUser = array(
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'password' => $user->password,
                'mobile' => $user->mobile,
                'avatar' => $user->avatar,
                'remember_token' => $user->remember_token,
                'role_id' => $user->role_id,
                'created_at' => date('Y-m-d H:m:s'),
                'updated_at' => date('Y-m-d H:m:s')
            );
            DeleteUser::insert($deleteUser);
            return redirect()
                ->route('admin.users')
                ->with([
                    'message' => "删除用户成功",
                    'alert-type' => 'success',
                ]);

        } else {
            $log = "删除用户" . $user->name . "失败";
            Logs::addLog($log);
            return redirect()
                ->route('admin.users')
                ->with([
                    'message' => "删除用户失败",
                    'alert-type' => 'error',
                ]);

        }

    }

    public
    function chooseNewUser(Request $requst)
    {
        $id = $requst->get('id');
//        $oldUser = User::find($id);
//        $newUsers = User::whereRaw("(city = ? and id <> ?) or id = 1",
//            array(
//                $oldUser['city'],
//                $oldUser['id']
//            ))->get();
        $newUsers = User::getNewUser($id);

        return $newUsers;
    }
}
